﻿package pl.kozulowski.loaders {
	
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	
	public class MultiLoader extends Loader {
		
		private var _queue:Array;
		private var _curr:int = 0;
		private var _req:URLRequest;
		private var _preloaded:Array;
		
		public function MultiLoader(){
			super();
			_queue = [];
			_preloaded = [];
		}
		
		public function addToQueue($url:String):void {
			_queue.push($url);
		}
		
		public function preload():void {
			if(_curr < _queue.length) {
				_req = new URLRequest(_queue[_curr]);
				super.contentLoaderInfo.addEventListener(Event.COMPLETE, onPreloaded);
				super.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError);
				super.load(_req);
			}
		}
		
		private function onPreloaded($e:Event):void {
			_preloaded.push(super.content);
			_curr++;
			if(_curr < _queue.length) {
				preload();
				dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS));
			}
			else dispatchEvent(new Event(Event.COMPLETE));
		}
		
		private function onError($e:IOErrorEvent):void {
			trace('Error laoding file: ' + _queue[_curr]);
		}
		
		public function get preloaded():Array {
			return _preloaded;
		}
		
		public function get progress():Number {
			return Number(_curr/_queue.length);
		}
		
		
	}
}